<?php
namespace addons\mall\controller;

use think\Db;
use app\common\model\mall\order\Order as OM;
use app\common\model\User as UM;
use app\common\model\mall\user\Extra as UEM;
use addons\mall\library\Base64;
use think\Exception;
use app\common\model\mall\oper\Msgtpl;
use addons\mall\library\Service;

/**
 * 余额控制器
 */
class Wallets extends Base{

	/**
	 * 生成支付代码
	 */
	function getWalletsUrl(){
		$orderNo = input('orderNo');
		$isBatch = (int)input('isBatch');
		$base64 = new Base64();
        $key = $this->Base64url($base64->encrypt($orderNo."_".$isBatch, "Mall"),true);
        $url = addon_url('mall/wallets/payment','key='.$key,'html',true);
		$this->success("",$url);
	}
	
	/**
	 * 跳去支付页面
	 */
	public function payment(){
		if((int)cookie('uid')==0){
			$this->assign('message',"对不起，您尚未登录，请先登录!");
            return $this->fetch('error_msg');
		}
		$user_id = (int)cookie('uid');
		$m = new UEM();
		$paypwd = $m->getFieldByUserId($user_id,"paypwd");
		$this->assign('hasPayPwd',($paypwd!="")?1:0);
		$key = input('key');
		$this->assign('paykey',$key);
        $key = $this->Base64url($key,false);
        $base64 = new Base64();
        $key = $base64->decrypt($key,"Mall");
        $key = explode('_',$key);
        $data = [];
        $data['orderNo'] = $key[0];
        $data['isBatch'] = (int)$key[1];
        $data['user_id'] = $user_id;
		$m = new OM();
		$rs = $m->getOrderPayInfo($data);
		if(empty($rs)){
            $this->success('您的订单已支付,即将进入订单管理页面','/user/mall/order/myorder?ref=addtabs');
		}else{
			$this->assign('needPay',$rs['needPay']);
			//获取用户钱包
            $um = new UM();
			$money = $um->getFieldById($data['user_id'],'money');
			$this->assign('money',$money);
	        return $this->fetch('/order/order_pay_wallets');
	    }
	}

	/**
	 * 钱包支付(扣除余额)
	 */
    public function payByWallet($uId=0,$type=0){
        $payPwd = input('payPwd');
        if(!$payPwd) $this->error('请输入密码');
        $key = input('key');
        $key = $this->Base64url($key,false);
        $base64 = new Base64();
        $key = $base64->decrypt($key,"Mall");
        $key = explode('_',$key);
        if(count($key)>1){
            $orderNo = $key[0];
            $isBatch = (int)$key[1];
        }else{
            $orderNo = input('orderNo');
            $isBatch = (int)input('isBatch');
        }
        $user_id = ($uId==0)?(int)cookie('uid'):$uId;
        //判断订单状态
        $where = ["user_id"=>$user_id,"status"=>"unpay","payis"=>0,"payType"=>1];
        if($isBatch==1){
            $where['orderunique'] = $orderNo;
        }else{
            $where['orderNo'] = $orderNo;
        }
        $orders = OM::field('id,orderNo,orderType,needPay,shop_id,payFrom,realTotalMoney')
            ->where($where)->select();
        if(count($orders)==0) $this->success('您的订单已支付,即将进入订单管理页面','/user/mall/order/myorder?ref=addtabs');
        //判断订单金额是否正确
        $needPay = 0;
        foreach ($orders as $v) {
            $needPay += $v->needPay;
        }
        //获取用户钱包
        $extra = UM::alias("u")
            ->join("__MALL_USER_EXTRA__ e","u.id=e.user_id","INNER")
            ->field("u.salt,u.money,e.paypwd")
            ->where("id",$user_id)->find();
        if(!$extra['paypwd']) $this->error('您未设置支付密码，请先设置密码',-1);

        if($extra['paypwd']!=md5($payPwd . $extra["salt"]))
            $this->error('您的支付密码不正确');
        if($needPay > $extra['money'])
            $this->error('您的钱包余额不足');

        //充值金额
        $rechargeMoney = $extra['money'];
        Db::startTrans();
        try{
            //循环处理每个订单
            foreach ($orders as $order) {
                //处理订单信息
                $tmpNeedPay = $order->needPay;
                $lockCashMoney = ($rechargeMoney>$tmpNeedPay)?$tmpNeedPay:$rechargeMoney;
                $order->needPay = 0;
                $order->payis = 1;//已支付
                $order->payTime = date('Y-m-d H:i:s');
                $order->status = "undeliver";//待发货
                $order->payFrom = 'wallets';
                //锁定金额，待客户收货后再结算给商家
                $order->lockCashMoney = $lockCashMoney;
                $result = $order->isUpdate(true)->allowField(true)->save();
                if(false != $result){
                    //创建一条支出流水记录
                    UM::money(-$tmpNeedPay, $this->auth->id, '交易订单【'.$order->orderNo.'】支出¥'.$tmpNeedPay);

                    //虚拟商品处理
                    if($order->orderType==1){
                        $this->handleVirtualGoods($order->id);
                    }
                    else{
                        //发送平台短信给管理员
                        $find = ['${ORDER_NO}'];
                        $replace = [$order['orderNo']];
                        $content = Msgtpl::getMsgByTpl('PHONE_ADMIN_PAY_ORDER', $find, $replace);
                        if ($content != '') {
                            Service::smsAdminNotice($content);
                        }
                    }
                }//end if
            }//end for
            Db::commit();
            $this->success('订单支付成功','/addons/mall/order/onlinePayCode?orderNo='.$orderNo);
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * URL 64位加密处理
     * @param string $data 字符串内容
     * @param boolean $isEncode true:编码  false:解码
     */
    function Base64url($data, $isEncode = true)
    {
        return ($isEncode) ? rtrim(strtr(base64_encode($data), '+/', '-_'), '=') : base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
    }

}
